package com.symaster.pdfcompose.util;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * @author yinmiao
 * @version 2024/4/29
 */
public class PDFUtil {
    public static InputStream toPDF(String imagePath) {

        try (PDDocument document = new PDDocument();
             ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {

            BufferedImage read = ImageIO.read(new File(imagePath));

            PDPage page = new PDPage(new PDRectangle(read.getWidth(), read.getHeight()));
            document.addPage(page);
            PDImageXObject pdImage = PDImageXObject.createFromFile(imagePath, document);

            PDPageContentStream contentStream = new PDPageContentStream(document, page);
            contentStream.drawImage(pdImage, 0, 0, pdImage.getWidth(), pdImage.getHeight());
            contentStream.close();

            document.save(byteArrayOutputStream);
            document.close();
            System.out.println("PDF created with image.");

            return new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
